package cn.tedu;

import java.sql.*;
import java.util.Scanner;

public class Demo04 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = scanner.nextLine();
        System.out.println("请输入密码:");
        String password = scanner.nextLine();
        try (Connection conn = DBUtils.getConn();)
        {
/*            Statement s = conn.createStatement();
//1            String sql ="select username,password from user where username='"+username+"' and password='"+password+"'";
              String sql = "select count(*) from user where username='"+username+"' and password='"+password+"'";
            ResultSet rs = s.executeQuery(sql);*/
            //*********解决SQL注入问题*****************
            //用?把变量的位置占上
            String sql = "select count(*) from user where username=? and password=?";
            //创建执行SQL语句对象
            /*jd
            预编译:由原来执行时编译,提前到了创建时编译,编译SQL语句时将SQL语句的业务逻辑锁死,
            编译后不会被用户输入的内容所影响
            */
            PreparedStatement ps = conn.prepareStatement(sql);
            //替换SQL语句中的?
            ps.setString(1,username);
            ps.setString(2,password);
            //不管用户输入什么,都会有结果,所以不用判断是否有下一条数据,直接移动游标
            ResultSet rs = ps.executeQuery();
            String username1 = rs.getString(1);
            String password1 = rs.getString(2);
            System.out.println(username1+","+password1);
            rs.next();
            int count = rs.getInt(1);
            if(count>0){
//1            if(rs.next()){
                System.out.println("登录成功!");
            }else {
                System.out.println("用户名或密码错误!");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
